home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14068 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: lrz-muenchen.de!news
  2. From: watzka@stat.uni-muenchen.de (Kurt Watzka)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to use assert( )
  5. Date: 11 Apr 1996 09:19:39 GMT
  6. Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
  7. Distribution: world
  8. Message-ID: <4kiirb$hll@sparcserver.lrz-muenchen.de>
  9. References: <4kc3k7$dur@orion.cybercom.net> <316be48b.3354928@news.netvision.net.il>
  10. NNTP-Posting-Host: sun2.lrz-muenchen.de
  11.  
  12. zivshosh@netvision.net.il ( Ziv) writes:
  13.  
  14. >On Mon, 08 Apr 1996 21:22:15 GMT, nield@cybercom.net (John Nield)
  15. >wrote:
  16.  
  17. >>I am interested in the use of the assert() library function (macro?).
  18. >>Neither the FAQ, nor K&R seems to have anything about it. Could
  19. >>someone help me with a breif explanation of its uses and mabye some
  20. >>example code? 
  21. >>
  22. >>I'm just starting my first project big enough to split among many
  23. >>people, and from the vague explanations I've heard, assert is supposed
  24. >>to be a usefull way to cause errors when someone passes your code bad
  25. >>values. How do I do this?
  26. >>
  27. >>thanx,
  28. >>
  29. >>;john nield
  30. >>
  31. >Suppose you read a number x which should be between xmin and xmax
  32. >after the reading you could write (assuming <assert.h> is #included)
  33. >assert( x >= xmin && x <= xmax);
  34.  
  35. This is how the macro assert() can be used in quick hacks. In real
  36. programs (i.e. programs that will be used more than once or twice),
  37. you usually check user input.
  38.  
  39. OTOH, if you have an algorithm that computes, e.g., a probability,
  40. then you know that the computed result will _always_ fall between
  41. two limits (0 and 1). So, in a function that returns a probability
  42. in  "res", the following statements might be useful to detect errors:
  43.  
  44.      assert(0.0 <= res && res <= 1.0);
  45.      return res;
  46.    }
  47.  
  48. The end user should never see the output of an assertion in an ideal
  49. world. One reason for this is that a final build should be translated 
  50. with NDEBUG defined. The other (more optimistic) reason is, that all
  51. possible problems that make an assertion fail should have been
  52. detected during testing.
  53.  
  54. Kurt
  55. -- 
  56. | Kurt Watzka                             Phone : +49-89-2180-6254
  57. | watzka@stat.uni-muenchen.de
  58.